package com.sinodata.bsm.cicp.collector.common;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.sinodata.bsm.cicp.collector.Collector;
import com.sinodata.bsm.cicp.exception.CollectorException;
import com.sinodata.bsm.common.constants.DataTypeConstants;
import com.sinodata.bsm.common.vo.ResPropertyValue;

/**
 * 
 * <p>
 * Description: （已废弃）URL监控(2012-12-18 被HttpRptServer)(Http模拟替代))
 * </p>
 *
 * @author liulibo
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2012-11-12 14:57:29      liulibo        1.0         To create
 * </p>
 *
 * @since 
 * @see
 */
public class Url extends Collector {

    private static final Logger logger = Logger.getLogger(HttpRptServer.class);

    //    private static String strMatch = "";

    public Url() {

    }

    /*
     * (non-Javadoc)
     * @see com.sinodata.bsm.cicp.collector.Collector#collect(java.lang.String)
     */
    @Override
    public List<ResPropertyValue> collect(String ip) throws CollectorException {
        String urlAddress = this.getParamMap().get("URL Address");//URL地址
        String match = this.getParamMap().get("Error Identification");//错误标识
        List<ResPropertyValue> value = getControlUrl(urlAddress, match);
        int i = 1;
        ResPropertyValue results = value.get(0);
        //如果连接不成功，在连续循环2两次，每次隔10秒钟
        while (results.getValues()[0].value.equals("FAILED") && (i++ < 3)) {
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                logger.error("Thread sleep error", e);
            }
            value = getControlUrl(urlAddress, match);
        }
        return value;
    }

    private List<ResPropertyValue> getControlUrl(String urlAddress, String match) {
        List<ResPropertyValue> values = new ArrayList<ResPropertyValue>();
        String[] propMetas = getPropMeta();
        ResPropertyValue propertyValueX = new ResPropertyValue();
        ResPropertyValue.PropValue[] propValues = new ResPropertyValue.PropValue[propMetas.length];
        // propValues[0] = ResPropertyValue.createPropValue("FAILED", propMetas[0]);
        propValues[0] = ResPropertyValue.createPropValue(DataTypeConstants.BOOLEAN_VALUE_FALSE, propMetas[0]);
        propValues[1] = ResPropertyValue.createPropValue("0", propMetas[1]);
        propValues[2] = ResPropertyValue.createPropValue("N/A", propMetas[2]);
        //StringBuffer fault = new StringBuffer();
        long startTime = System.currentTimeMillis();
        BufferedReader bfr = null;
        String line = "";
        HttpURLConnection connection = null;
        try {
            URL url = new URL(urlAddress);
            //识别该url对应页面的字符集
            connection = (HttpURLConnection) url.openConnection();
            String ct = connection.getContentType();
            String charset = ct.split("charset=")[1];
            bfr = new BufferedReader(new InputStreamReader(url.openStream(), charset));
            //url连接耗时
            long endTime = System.currentTimeMillis() - startTime;
            propValues[0] = ResPropertyValue.createPropValue(DataTypeConstants.BOOLEAN_VALUE_TRUE, propMetas[0]);
            propValues[1] = ResPropertyValue.createPropValue(String.valueOf(endTime), propMetas[1]);
            propValues[2] = ResPropertyValue.createPropValue(DataTypeConstants.BOOLEAN_VALUE_FALSE, propMetas[2]);
            //当有错误标识
            if (match.length() > 0) {
                String[] matchs = match.split(",");
                while ((line = bfr.readLine()) != null) {
                    for (int i = 0; i < matchs.length; i++) {
                        if (line.indexOf(matchs[i]) > -1) {
                            propValues[2] = ResPropertyValue.createPropValue(DataTypeConstants.BOOLEAN_VALUE_TRUE, propMetas[2]);
                            break;
                        }
                        /*int index = line.indexOf(matchs[i]);
                        int faultIndex = fault.indexOf(matchs[i]);
                        if ((index >= 0) && (faultIndex == -1)) {
                            fault.append(matchs[i] + " ");
                        }*/
                    }
                }
            }
            /*if (fault.length() > 0) {
                propValues[2] = ResPropertyValue.createPropValue(DataTypeConstants.BOOLEAN_VALUE_TRUE, propMetas[2]);
            } else {
                propValues[2] = ResPropertyValue.createPropValue(DataTypeConstants.BOOLEAN_VALUE_FALSE, propMetas[2]);
            }*/
            propertyValueX.setValues(propValues);
            values.add(propertyValueX);
        } catch (Exception e) {
            propertyValueX.setValues(propValues);
            values.add(propertyValueX);
            return values;
        } finally {
            if (bfr != null) {
                try {
                    bfr.close();
                } catch (IOException e) {
                    logger.error("failed to close BufferedReader", e);
                }
            }
            if (connection != null) {
                connection.disconnect();
            }
        }
        return values;
    }

    /*
     * (non-Javadoc)
     * @see com.sinodata.bsm.cicp.collector.Collector#getParamMeta()
     */
    @Override
    public String[] getParamMeta() {
        //        return new String[] { "URL地址", "错误标识" };
        return new String[] { "URL Address", "Error Identification" };
    }

    /*
     * (non-Javadoc)
     * @see com.sinodata.bsm.cicp.collector.Collector#getPropMeta()
     */
    @Override
    public String[] getPropMeta() {
        //        return new String[] { "是否成功", "URL连接耗时", "是否产生错误" };
        return new String[] { "Whether_Successful", "URL_Connection_Time", "Whether_Create_Error" };
    }

}
